package com.Logistics.pddispatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.Logistics.pddispatch.entity.CacheLine;
import com.Logistics.pddispatch.mapper.CacheLineMapper;
import com.Logistics.pddispatch.service.CacheLineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class CacheLineServiceImpl extends ServiceImpl<CacheLineMapper, CacheLine> implements CacheLineService {
    @Autowired
    private CacheLineMapper cacheLineMapper;
    @Override
    public String check(String verify_key) {
        QueryWrapper<CacheLine> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(verify_key)){
            queryWrapper.eq("verify_key",verify_key);
            queryWrapper.eq("is_current",1);
        }
        CacheLine cacheLine = this.cacheLineMapper.selectOne(queryWrapper);
        return cacheLine.getId();
    }

    @Override
    public Integer deleteOldAndGetNewVersion(String notEqualsLineStart, String notEqualsLineEnd) {
        Integer version = 0;
        QueryWrapper<CacheLine> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(notEqualsLineStart)){
            queryWrapper.eq("start_agency_id",notEqualsLineStart);
        }
        if (StringUtils.hasText(notEqualsLineEnd)){
            queryWrapper.eq("end_agency_id",notEqualsLineEnd);
        }
        queryWrapper.eq("is_current",1);

        List<CacheLine> lines = this.cacheLineMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(lines)) {
            version = lines.get(0).getVersion();

            CacheLine cacheLine = new CacheLine();
            cacheLine.setIs_current(0);
            UpdateWrapper<CacheLine> lineBeanUpdateWrapper = new UpdateWrapper<>();
            if (StringUtils.hasText(notEqualsLineStart)){
                lineBeanUpdateWrapper.eq("start_agency_id",notEqualsLineStart);
            }
            if (StringUtils.hasText(notEqualsLineEnd)){
                lineBeanUpdateWrapper.eq("end_agency_id",notEqualsLineEnd);
            }
            queryWrapper.eq("is_current",1);
            this.cacheLineMapper.update(cacheLine,lineBeanUpdateWrapper);
        }
        return ++version;
    }
}
